package com.pms.partitionPoints.web;

import com.pms.exception.R;
import com.pms.partitionPoints.entity.KyEquipmentUploadData;
import com.pms.partitionPoints.entity.KyOrganization;
import com.pms.partitionPoints.service.IKyGroupOrganizationService;
import com.pms.partitionPoints.service.IKyOrganizationService;
import com.pms.util.DateUtil;
import com.pms.validator.Assert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.web.bind.annotation.*;
import com.pms.controller.BaseController;
import com.pms.partitionPoints.service.IKyOrganizationEquipmentService;
import com.pms.partitionPoints.entity.KyOrganizationEquipment;
import com.pms.result.JsonResult;
import com.pms.result.ObjectRestResponse;
import com.pms.result.TableResultResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("kyOrganizationEquipment")
@Api(value="分区测点管理",description = "分区测点管理")
public class KyOrganizationEquipmentController extends BaseController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    IKyOrganizationEquipmentService kyOrganizationEquipmentService;
    @Autowired
    IKyOrganizationService kyOrganizationService;
    @Autowired
    IKyGroupOrganizationService kyGroupOrganizationService;

    /**
         * 新增
         * @param entity
         * @return
         */
    @RequestMapping(value = "",method = RequestMethod.POST)
    @ResponseBody
    public ObjectRestResponse<KyOrganizationEquipment> add(@RequestBody KyOrganizationEquipment entity){
            kyOrganizationEquipmentService.insert(entity);
        return new ObjectRestResponse<KyOrganizationEquipment>().rel(true);
    }
    /**
     * 修改
     * @param entity
     * @return
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.POST)
    @ResponseBody
    public ObjectRestResponse<KyOrganizationEquipment> update(@RequestBody KyOrganizationEquipment entity){
            kyOrganizationEquipmentService.updateById(entity);
        return new ObjectRestResponse<KyOrganizationEquipment>().rel(true);
    }

    /**
 * 删除
 * @param id
 * @return
 */
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public ObjectRestResponse<KyOrganizationEquipment> deleteById(@PathVariable int id){
            kyOrganizationEquipmentService.deleteById (id);
        return new ObjectRestResponse<KyOrganizationEquipment>().rel(true);
    }


    /**
     * findByID
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<KyOrganizationEquipment> findById(@PathVariable int id){
        return new ObjectRestResponse<KyOrganizationEquipment>().rel(true).data( kyOrganizationEquipmentService.selectById(id));
    }


    @RequestMapping(value = "/page",method = RequestMethod.GET)
    @ResponseBody
    public TableResultResponse<KyOrganizationEquipment> page(@RequestParam(defaultValue = "10") int limit, @RequestParam(defaultValue = "1")int offset){
        Page<KyOrganizationEquipment> page = new Page<KyOrganizationEquipment>(offset,limit);
        page = kyOrganizationEquipmentService.selectPage(page,new EntityWrapper<KyOrganizationEquipment>());
        return new TableResultResponse<KyOrganizationEquipment>(page.getTotal(),page.getRecords());
    }

    @RequestMapping(value = "/all",method = RequestMethod.GET)
    @ResponseBody
    public List<KyOrganizationEquipment> all(){
        return kyOrganizationEquipmentService.selectList(null);
    }

    /**
     * 计量分区曲线分析
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/getOrgCurveAnalysis",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "计量分区曲线分析")
    @ApiImplicitParams({
            @ApiImplicitParam(name="orgMaxId",value="系统id(顶级分区id)",required = true,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="orgId",value="分区id",required = true,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="startTime",value="开始时间",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="endTime",value="结束时间",required = true,dataType = "String",paramType="form")
    })
    public R getEquipmentCurveAnalysis(Integer orgMaxId,Integer orgId, String startTime, String endTime){
        Assert.isNull(orgMaxId,"系统id不能为空");
        Assert.isNull(orgId,"分区id不能为空");
        Assert.isNull(startTime,"开始时间不能为空");
        Assert.isNull(endTime,"结束时间不能为空");
        Date startDate = DateUtil.stringToDate(startTime);
        Date endDate = DateUtil.stringToDate(endTime);
        List<Map<String,Object>> list = kyOrganizationEquipmentService.getOrgWaterDayByEquIdsAdTime(orgMaxId,orgId,startDate,endDate);//产销差，漏损量，漏损率
        return R.ok().put("data",list);
    }

    /**
     * 计量分区耗水量分析
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/getOrgWaterUsageByOrgId",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "计量分区耗水量分析")
    @ApiImplicitParams({
            @ApiImplicitParam(name="orgMaxId",value="系统id(顶级分区id)",required = true,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="orgId",value="分区id",required = true,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="startTime",value="开始时间",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="endTime",value="结束时间",required = true,dataType = "String",paramType="form")
    })
    public R getOrgWaterUsageByOrgId(Integer orgMaxId,Integer orgId, String startTime, String endTime){
        Assert.isNull(orgMaxId,"顶级分区id不能为空");
        Assert.isNull(orgId,"分区id不能为空");
        KyOrganization kyOrganization = kyOrganizationService.selectById(orgId);
        Assert.isNull(kyOrganization,"没有此分区");
        Assert.isNull(startTime,"开始时间不能为空");
        Assert.isNull(endTime,"结束时间不能为空");
        Date startDate = DateUtil.stringToDate(startTime);
        Date endDate = DateUtil.stringToDate(endTime);
        String type = request.getHeader("X-groupType");//type:1.系统默认 2.自定义
        Assert.isBlank(type,"用户类型不能为空");
        String roleId = request.getHeader("X-groupId");
        Assert.isBlank(roleId,"角色id不能为空");
        List<KyOrganization> koList = new ArrayList<>();//下级分区列表
        if(type.equals("2")){
            int organizationgradeid = kyOrganization.getOrganizationgradeid();
            String ids = kyGroupOrganizationService.getOrgIdsStrByGroupId(roleId);
            String [] arr = ids.split(",");
            if(arr.length>0){
                List<KyOrganization> kyList = kyOrganizationService.selectList(new EntityWrapper<KyOrganization>().in("id",arr));
                for(int i=0;i<kyList.size();i++){
                    KyOrganization ko = kyList.get(i);
                    if(ko.getOrganizationgradeid()==organizationgradeid+1&&ko.getParentid()==orgId.intValue()){
                        koList.add(ko);
                    }
                }
            }else{
                return R.error("此用户没有绑定对应的分区");
            }
        }else{
            koList = kyOrganizationService.selectList(new EntityWrapper<KyOrganization>().eq("parentId",orgId));
        }
        Map<String,Object> map = new HashMap<>();//返回数据
        Map<String,Object> flowMap = new HashMap<>();//上级分区
        List<Map<String,Object>> list = new ArrayList<>();
//        if(startTime.equals(endTime)){
//            BigDecimal countInstantaneousFlow = kyOrganizationEquipmentService.getNewestFlowByOrgId(orgMaxId,orgId,startDate);
//            flowMap.put("orgId",orgId);
//            flowMap.put("value",countInstantaneousFlow);
//            flowMap.put("name",kyOrganization.getName());
//            flowMap.put("parentId",kyOrganization.getParentid());
//            map.put("flowMap",flowMap);
//            if(koList.size()>0){
//                for(KyOrganization ko:koList){
//                    Map<String,Object> newMap = new HashMap<>();
//                    BigDecimal flow = kyOrganizationEquipmentService.getNewestFlowByOrgId(orgMaxId,ko.getId(),startDate);
//                    newMap.put("orgId",ko.getId());
//                    newMap.put("value",flow);
//                    newMap.put("name",ko.getName());
//                    list.add(newMap);
//                }
//            }
//            map.put("list",list);
//        }else{
            BigDecimal countInstantaneousFlow = kyOrganizationEquipmentService.selectOrgWaterUsageByOrgIdAndTime(orgMaxId,orgId,startDate,endDate);//当前分区
            flowMap.put("orgId",orgId);
            flowMap.put("value",countInstantaneousFlow);
            flowMap.put("name",kyOrganization.getName());
            flowMap.put("parentId",kyOrganization.getParentid());
            map.put("flowMap",flowMap);
            //下级分区
            if(koList.size()>0){
                for(KyOrganization ko:koList){
                    Map<String,Object> newMap = new HashMap<>();
                    BigDecimal flow = kyOrganizationEquipmentService.selectOrgWaterUsageByOrgIdAndTime(orgMaxId,ko.getId(),startDate,endDate);//下级分区
                    newMap.put("orgId",ko.getId());
                    newMap.put("value",flow);
                    newMap.put("name",ko.getName());
                    list.add(newMap);
                }
            }
            map.put("list",list);
//        }
        return R.ok().put("data",map);
    }

}